from flask import request, jsonify
from ..models.signup_record import SignupRecord
from ..models.event import Event
from ..extensions import db
from ..utils.response import pagination, error, success
from datetime import datetime

# 创建报名记录
def create_signup_record(data):
    
    # 检查必填字段
    required_fields = ['name', 'phone', 'activity_id']
    for field in required_fields:
        if field not in data:
            return error(f"{field} is required", 400)
    
    # 验证活动是否存在
    activity_id = data.get('activity_id')
    try:
        activity_id = int(activity_id)
    except ValueError:
        return error("Invalid activity ID", 400)
    
    event = Event.query.get(activity_id)
    if not event:
        return error("Activity not found", 404)
    
    # 验证当前时间是否在报名时间段内
    current_time = datetime.utcnow()
    if current_time < event.registration_start_time or current_time > event.registration_end_time:
        return error("Registration is not open", 400)
    
    # 检查手机号是否已报名该活动
    existing_record = SignupRecord.query.filter_by(
        phone=data['phone'],
        activity_id=activity_id
    ).first()
    if existing_record:
        return error("You have already signed up for this activity", 400)
    
    # 创建报名记录
    signup_record = SignupRecord(
        name=data['name'],
        phone=data['phone'],
        activity_id=activity_id,
        signup_time=datetime.utcnow()
    )
    
    db.session.add(signup_record)
    db.session.commit()
    
    return success(signup_record.to_dict(),"Sign up successfully")

# 获取报名记录列表
def get_signup_records(data):
    """获取报名记录列表，支持分页和按活动ID筛选"""
    try:
        # 连表查询
        query = db.session.query(SignupRecord, Event.name).join(Event, SignupRecord.activity_id == Event.id)
        
        # 按活动ID筛选
        activity_id = data.get('activity_id')
        if activity_id:
            try:
                activity_id = int(activity_id)
                query = query.filter_by(activity_id=activity_id)
            except ValueError:
                return error("Invalid activity ID", 400)
        
        # 计算总数
        total = query.count()
        
        # 按报名时间倒序排列
        query = query.order_by(SignupRecord.signup_time.desc())
        
        # 获取分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 处理无效的分页参数
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100  # 限制最大每页记录数
        
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 获取分页数据
        records = query.offset(offset).limit(page_size).all()
        
        records = [
            {
                **record.to_dict(),
                'event_name': event_name
            }
            for record, event_name in records
        ]

        # 返回分页数据
        return pagination(
            items=records,
            total=total,
            msg='获取成功',
            code=200
        )
    except Exception as e:
        return error('获取失败', 500)

# 获取单个报名记录信息
def get_signup_record(data):
    # 从请求参数中获取报名记录ID
    record_id = data.get('id')
    
    if not record_id:
        return error("Record ID is required", 400)
    
    try:
        record_id = int(record_id)
    except ValueError:
        return error("Invalid record ID", 400)
    
    record = SignupRecord.query.get(record_id)
    if not record:
        return error("Record not found", 404)
    
    return success(record.to_dict(), "Record found")

# 更新报名记录信息
def update_signup_record(data):
    
    # 从请求数据中获取报名记录ID
    record_id = data.get('id')
    
    if not record_id:
        return error("Record ID is required", 400)
    
    try:
        record_id = int(record_id)
    except ValueError:
        return error("Invalid record ID", 400)
    
    record = SignupRecord.query.get(record_id)
    if not record:
        return error("Record not found", 404)
    
    # 更新报名记录信息
    if 'name' in data:
        record.name = data['name']
    
    if 'phone' in data:
        # 检查新手机号是否已报名该活动
        existing_record = SignupRecord.query.filter_by(
            phone=data['phone'],
            activity_id=record.activity_id
        ).first()
        if existing_record and existing_record.id != record_id:
            return error("This phone number has already signed up for this activity", 400)
        record.phone = data['phone']
    
    if 'activity_id' in data:
        try:
            activity_id = int(data['activity_id'])
            event = Event.query.get(activity_id)
            if not event:
                return error("Activity not found", 404)
            record.activity_id = activity_id
        except ValueError:
            return error("Invalid activity ID", 400)
    
    db.session.commit()
    
    return success("Record updated successfully", record.to_dict())

# 删除报名记录
def delete_signup_record(data):
    # 从请求数据中获取报名记录ID
    record_id = data.get('id')
    
    if not record_id:
        return error("Record ID is required", 400)
    
    try:
        record_id = int(record_id)
    except ValueError:
        return error("Invalid record ID", 400)
    
    record = SignupRecord.query.get(record_id)
    if not record:
        return error("Record not found", 404)
    
    db.session.delete(record)
    db.session.commit()
    
    return success("Record deleted successfully")